package tech.aistar.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.session.SqlSession;
import tech.aistar.mapper.PhoneMapper;
import tech.aistar.pojo.Phone;
import tech.aistar.service.IPhoneService;
import tech.aistar.until.MybatisUtil;

import java.util.List;

/**
 * @author Ray
 * @version 1.0
 * @description:本类用来演示:
 * @date 2019/9/6  18:01
 */
public class PhoneServiceImpl implements IPhoneService {
    @Override
    public List<Phone> findAll(String name, Integer typeId) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        List<Phone> list = mapper.findAll(name,typeId);
        sqlSession.close();

        return list;
    }

    @Override
    public void delById(Integer id) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        mapper.delById(id);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void insert(Phone p) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        mapper.insert(p);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public Phone findById(Integer id) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        Phone phone = mapper.findById(id);

        sqlSession.commit();
        sqlSession.close();

        return phone;
    }

    @Override
    public void updateById(Phone phone) {
        SqlSession sqlSession = MybatisUtil.getSqlSession();
        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        mapper.updateById(phone);

        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public PageInfo<Phone> findAll(String name, Integer typeId, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);

        SqlSession sqlSession = MybatisUtil.getSqlSession();

        PhoneMapper mapper = sqlSession.getMapper(PhoneMapper.class);

        List<Phone> phoneList = mapper.findAll(name,typeId);

        PageInfo<Phone> pageInfo = new PageInfo<>(phoneList);


        sqlSession.commit();

        MybatisUtil.close(sqlSession);

        return pageInfo;
    }
}
